<?php


namespace Module\DyAi\Api\Controller;

use Illuminate\Routing\Controller;
use ModStart\Core\Dao\ModelUtil;
use ModStart\Core\Input\InputPackage;
use ModStart\Core\Input\Response;
use Module\DyAi\Model\DownContent;
use Module\DyAi\Model\DyAiCategory;
use Module\DyAi\Model\DyAiKeysugg;
use DOMDocument;
use GuzzleHttp\Client;

/**
 * @Api 当游网ai助手
 */
class AiController extends Controller
{

    
    /**
     * @Api 推送内容
     */
    public function push_content()
    {
		try{
		$input = InputPackage::buildFromInput();
		$min_id = $input->getInteger('min_id')?$input->getInteger('min_id'):0;
		$max_id = $input->getInteger('max_id')?$input->getInteger('max_id'):9999999;
        $result = DownContent::whereNull('ai_json')->where('id','>',$min_id)->where('id','<',$max_id)->whereIn('cat_type',[1])->first();//207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,227,226,228,229,230
		if($result){
			$url = 'http://gs2.3h3.com:8082/DyV2.aspx?api=GetAIToken';
			$client = new Client;
			$response = $client->post($url,['form_params'=>['id'=>$result['ai_role_id'],'did'=>6,'get_content'=>1]]);
			$json = json_decode($response->getBody(),true);
			$url = 'http://gs2.3h3.com:8082/DyV2.aspx?api=GetAIContent';
			$text = $result['content'];//var_dump($text);
			$response = $client->post($url, [  
							'form_params' => [ // 使用 form_params 而不是 content，它会自动 URL 编码  
								'content' => $text,  
								'SubmitFormat' => 1,  
							],  
							'headers' => [  
								'Content-Type' => 'application/x-www-form-urlencoded', // 明确设置 Content-Type  
							],  
						]);//var_dump(json_decode($response->getBody()));
			$json2 = json_decode($response->getBody(),true);
			$text_json = $json2['datas']?$json2['datas']:$text;
			$content = $json['datas'][0]['token_json']['GPStartStr'].$text_json;//
			$url = 'http://gs2.3h3.com:1881/gpt';//var_dump($json);
			$post_arr = ['api'=>'gpt','token_id'=>$result['ai_role_id'],'cuetip'=>$json['datas'][0]['token_json']['GPStartStr'],'content'=>$content,'CallBackUrl'=>'http://'.$_SERVER['HTTP_HOST'].'/api/ai/callback_content?id='.$result['id']];
			$response = $client->post($url, [
							'json' => $post_arr,  
							'headers' => [  
								'Content-Type' => 'application/json', // 明确设置 Content-Type  
							],  
						]);
						
						//echo json_encode($post_arr);
						//var_dump(json_encode($response->getBody()));
			$json3 = json_decode($response->getBody(),true);
			return Response::generate(200, 'ai标签已更新完',['create'=>'success','id'=>$result['id']]);
			return Response::generate(200, '已提交标签读取id:'.$result['id'],['url'=>'http://'.$_SERVER['HTTP_HOST'].'/api/ai/push_content?min_id='.$result['id'].'&max_id=9999999','id'=>$result['id']]);
		}else{
			return Response::generate(200, 'ai标签已更新完',['create'=>'success','id'=>$result['id']]);
		}
		}catch(\Exception $e){
			return Response::generateError('ai标签更新出错'.$e->getMessage());
			//var_dump($e->getMessage());
		}
			
    }

    /**
     * @Api 回调
     */
    public function callback_content()
    {
        $input = InputPackage::buildFromInput();
        $SignMD5 = $input->getTrimString('SignMD5');
        $code = $input->getInteger('code');
        $id = $input->getInteger('id');
		if($code != 200)return Response::generateSuccessData([]);
		if(!$id)return Response::generateSuccessData([]);
        $content = $input->getTrimString('result_content');
        $downcontent = DownContent::where(['id' => $id])->first();
        //$downcontent->ai_json = $content;
        //if(trim($content)!='')$result = $downcontent->save();
		$pattern = '/\{(.*?)\}/s'; // 使用s修饰符使得点号可以匹配换行符  
		$str = $content;
		if (preg_match($pattern, $str, $matches)) {
			// $matches[1] 将包含第一个匹配的大括号内的内容  
			$jsonString = $matches[0];  
			// 为了确保内容是有效的JSON，可以使用json_decode进行验证  
			$jsonData = json_decode($jsonString, true);  
			if ($jsonData !== null && json_last_error() === JSON_ERROR_NONE) {  
				$content = $jsonString;
			} else {
			}
		}
		$result = '';
		if(trim($content)!='' && $downcontent){
			$result = DownContent::where('softname', $downcontent['softname'])->update(['ai_json' => $content]);  
		}
        return Response::generateSuccessData($result);
    }
	function tryConvertToUtf8AndDecode($jsonString, $possibleEncodings = ['GBK', 'GB2312', 'BIG5', 'ISO-8859-1', 'Windows-1252']) {  
		foreach ($possibleEncodings as $encoding) {  
			$utf8String = @mb_convert_encoding($jsonString, 'UTF-8', $encoding); // 使用@来抑制可能的警告  
			$result = json_decode($utf8String, true);  
			if (json_last_error() === JSON_ERROR_NONE) {  
				// 成功解析 JSON  
				return $result;  
			}  
		}  
		  
		// 所有尝试都失败了  
		return null;  
	}  
	
	function generateKeywordCombinations($baseKey, $keywordArrays, $currentCombination = '') {  
		$results = [];  
		  
		// 如果没有关键词数组了，说明已经处理完所有嵌套，将当前组合添加到结果中  
		if (empty($keywordArrays)) {  
			$results[] = $baseKey . $currentCombination;  
			return $results;  
		}  
		  
		// 取出第一个关键词数组进行处理  
		$firstArray = array_shift($keywordArrays);  
		  
		// 遍历当前关键词数组的所有元素  
		foreach ($firstArray as $keyword) {  
			// 递归调用 generateKeywordCombinations 来处理剩下的关键词数组  
			// 同时传入新的组合字符串（当前组合 + 当前关键词）  
			$subCombinations = generateKeywordCombinations($baseKey, $keywordArrays, $currentCombination . $keyword);  
			  
			// 将递归返回的结果合并到当前结果中  
			$results = array_merge($results, $subCombinations);  
		}  
		  
		// 如果还有未处理的关键词数组，将它们放回到 $keywordArrays 中，以便下一次递归调用  
		if (!empty($keywordArrays)) {  
			array_unshift($keywordArrays, $firstArray);  
		}  
		  
		return $results;  
	}
	public function getLastKey($key){
		$keywordA = modstart_config('DyAi_keywordA','')?explode(PHP_EOL,modstart_config('DyAi_keywordA','')):[];
		$keywordB = modstart_config('DyAi_keywordB','')?explode(PHP_EOL,modstart_config('DyAi_keywordB','')):[];
		$keywordC = modstart_config('DyAi_keywordC','')?explode(PHP_EOL,modstart_config('DyAi_keywordC','')):[];
		$keywordD = modstart_config('DyAi_keywordD','')?explode(PHP_EOL,modstart_config('DyAi_keywordD','')):[];
		foreach ($keywordA as $a_i => $a) {
			$key_link = $key . $a;  
			if (count($keywordB) > 0) {  
				foreach ($keywordB as $b_i => $b) {  
					$key_link .= $b;  
					if (count($keywordC) > 0) {  
						foreach ($keywordC as $c_i => $c) {  
							$key_link .= $c;  
							if (count($keywordD) > 0) {  
								foreach ($keywordD as $d_i => $d) {  
									$key_link .= $d;  
									$keys[] = $key_link;  
								}  
							} else {  
								$keys[] = $key_link;  
							}  
							// 重置 $key_link，去掉最后一个 $c  
							$key_link = rtrim($key_link, $c);  
						}  
					} else {  
						$keys[] = $key_link;  
					}  
					// 重置 $key_link，去掉最后一个 $b  
					$key_link = rtrim($key_link, $b);  
				}  
			} else {  
				$keys[] = $key_link;  
			}  
			// 在这里不需要重置 $key_link，因为它在下一次迭代时会自动被新的 $a 重置  
		}
		return $keys;
	}
    /**
     * @Api 校验百度关键词key
     */
    public function check_keyword_by_baidu_old()
    {
		/*$jsonString = '{"q":"高度定制的web浏览器","p":true,"s":["高度定制的web浏览器有哪些","高度定制的web浏览器是什么","高度定制的web浏览器","简单的web浏览器设计","定制版浏览器","主流web浏览器","浏览器设计","web浏览器设置在哪里","浏览器网页设计","浏览器插件定制"]}';  
  
		$array = json_decode($jsonString, true); // 第二个参数为 true，将返回关联数组而不是对象  
		  
		if (json_last_error() === JSON_ERROR_NONE) {  
			// 成功解析 JSON  
			print_r($array);  
		} else {  
			// 解析 JSON 失败  
			echo 'JSON 解析错误: ' . json_last_error_msg();  
		}  exit;*/
		
        $input = InputPackage::buildFromInput();
        $content = $input->getTrimString('result_content');
        $downcontent = DownContent::whereNotNull('ai_json')->where(['is_keyword_read' => 0])->first();
		$ai_json = json_decode($downcontent->ai_json,true);
		$keys = $ai_json['comprehensive_keywords'];
		$client = new Client;
		$result = [];
        foreach($keys as $k=>$key){
			$key_links = $this->getLastKey($key);
			foreach($key_links as $l=>$keyl){
				$search_keyword = substr($keyl, 0, -1);
				$sugg_count = DyAiKeysugg::where(['search_keyword' => $search_keyword])->count();
				if($sugg_count == 0){
					$url = 'http://suggestion.baidu.com/su?ie=utf-8&wd='.$search_keyword;
					$response = $client->get($url);
					$pattern = '/(\w+):/i'; // 匹配未带引号的键（这里假设键是单词字符组成的）  
					$replacement = '"$0":'; // 替换为带引号的键  
					$fixedJson = preg_replace('/(\w+)(?=:)/', '"$1"', str_replace(['window.baidu.sug(',');'],'',$response->getBody()));
					// 使用 json_decode 和 json_encode 来确保格式正确  
					// 注意：如果 json_decode 失败，将返回原始字符串  
					$arr = json_decode($fixedJson, true);
					if ($arr !== null) {
						//if(count($arr['s']) > 0){
							$arr = ['keyword'=>$key,'search_keyword' => $search_keyword,'sugg_json'=>$fixedJson];
							$insert_result = ModelUtil::insert('dy_ai_keysugg', $arr);
							$result[] = $search_keyword;
						//}
					}
				}
			}
		}
		$downcontent->is_keyword_read = 1;
        if(count($result)>0)$update_result = $downcontent->save();
        return Response::generateSuccessData($result);
    }
	
    /**
     * @Api 校验百度关键词key
     */
    public function check_keyword_by_baidu()
    {
		$filterwords = modstart_config('DyAi_filterword','')?explode(PHP_EOL,modstart_config('DyAi_filterword','')):[];
        $nowords = modstart_config('DyAi_noword','')?explode(PHP_EOL,modstart_config('DyAi_noword','')):[];
        $input = InputPackage::buildFromInput();
        $content = $input->getTrimString('result_content');
        $downcontent = DownContent::whereNotNull('ai_json')->where(['is_keyword_read' => 0])->first();
		$result = [];
		try{
		$ai_json = json_decode($downcontent->ai_json,true);
		$keys = $ai_json['comprehensive_keywords'];
		$client = new Client;
		$result['id'] = $downcontent->id;
        foreach($keys as $k=>$key){
			$istrue = false;
			foreach($filterwords as $fk=>$word){
				if (substr_compare($key, $word, -strlen($word)) === 0) {
					$istrue = true;
					break;
				}
			}
			foreach($nowords as $fk=>$word){
				if (substr_compare($key, $word, -strlen($word)) === 0) {
					$istrue = false;
					break;
				}
			}
			if($istrue && strstr($key,$downcontent->softname) == false){
				$search_keyword = mb_substr($key, 0, -1);
				$sugg_count = DyAiKeysugg::where(['search_keyword' => $search_keyword])->count();
				if($sugg_count == 0){
					$url = 'http://suggestion.baidu.com/su?ie=utf-8&wd='.$search_keyword;
					$response = $client->get($url);
					$pattern = '/(\w+):/i'; // 匹配未带引号的键（这里假设键是单词字符组成的）  
					$replacement = '"$0":'; // 替换为带引号的键  
					$fixedJson = preg_replace('/(\w+)(?=:)/', '"$1"', str_replace(['window.baidu.sug(',');'],'',$response->getBody()));
					// 使用 json_decode 和 json_encode 来确保格式正确  
					// 注意：如果 json_decode 失败，将返回原始字符串  
					$arr = json_decode($fixedJson, true);
					if ($arr !== null) {
						//if(count($arr['s']) > 0){
							$arr = ['keyword'=>$key,'search_keyword' => $search_keyword,'sugg_json'=>$fixedJson];
							$insert_result = ModelUtil::insert('dy_ai_keysugg', $arr);
							$result['keys'][] = $key;
						//}
					}
				}
			}
		}
		$downcontent->is_keyword_read = 1;
        if(count($result)>0)$update_result = $downcontent->save();
		}catch(\Exception $e){$downcontent->ai_json = null;$update_result = $downcontent->save();}
        return Response::generateSuccessData($result);
    }
	
	
	
}
